using System.IO;
using System.Net;

namespace Pornotube
{
    public class Worker
    {
        public bool CheckURL(string url)
        {
            string prefix   = "http://www.pornotube.com";
            if (url.IndexOf(prefix) >= 0)
                return true;
            else 
                return false;
        }
        
        public string GetSource(string sourceURL)
        {
            string pageContent  = getPage(sourceURL);
            string decollator   = "v.swf?v=";
            string right        = pageContent.Substring(pageContent.IndexOf(decollator) + decollator.Length);
            string id           = right.Substring(0, right.IndexOf("\""));
            
            string newURL       = string.Format("http://www.pornotube.com/player/player.php?{0}", id);
            pageContent         = getPage(newURL);
            
            decollator          = "<media_id>";
            right               = pageContent.Substring(pageContent.IndexOf(decollator) + decollator.Length);
            string media_id     = right.Substring(0, right.IndexOf("<"));
            
            decollator          = "<user_id>";
            right               = pageContent.Substring(pageContent.IndexOf(decollator) + decollator.Length);
            string user_id      = right.Substring(0, right.IndexOf("<"));
            
            string result       = string.Format("http://video.pornotube.com/{0}/{1}.flv", user_id, media_id);
            return result;
        }
        
        private string getPage(string uri)
        {
            WebRequest request      = WebRequest.Create(uri);
            WebResponse response    = request.GetResponse();
            
            Stream dataStream       = response.GetResponseStream();
            StreamReader reader     = new StreamReader(dataStream);
            string responseFS       = reader.ReadToEnd();
            
            reader.Close();
            response.Close();
            
            return responseFS;
        }
    }
}
